import re

from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

from apps.member.diary.models import Diary
from apps.system.models import Config

from utils.exception import CustomError
from utils.DFA import DFAFilter


# Create your models here.
class Member(models.Model):
    COMMON = 0
    PRIMARY = 1
    SENIOR = 2
    MEMBER_LEV_CHOICES = (
        (COMMON, '普通会员'),
        (PRIMARY, '初级会员'),
        (SENIOR, '高级会员')
    )

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, editable=False, related_name='member', on_delete=models.PROTECT, verbose_name='会员'
    )

    headImage = models.CharField(verbose_name='头像', max_length=200, null=True)
    balance = models.BigIntegerField(verbose_name='余额', editable=False, default=0)
    level = models.PositiveSmallIntegerField(verbose_name='会员等级', default=COMMON, editable=False)
    validity_time = models.DateTimeField(verbose_name='会员有效时间', null=True, editable=False)

    @staticmethod
    def check_name_legal(name):
        # 替换字符串中的匹配项  \s:匹配任意空白字符  []:用来表示一组字符  +:匹配1个或多个的表达式
        nickname = re.sub("[\s ]+", "", name)
        """
        在字符串中，包含换行符\n，在这种情况下：
        如果不使用re.S参数，则只在每一行内进行匹配，如果一行没有，就换下一行重新开始。
        而使用re.S参数以后，正则表达式会将这个字符串作为一个整体，在整体中进行匹配。
        """

        m = re.search("\d{7,}", name, re.S)

        if m:
            raise CustomError('请不要包含QQ号（群）等联系方式，否则可能被系统禁言或封号！')

        dfa = DFAFilter()
        dfa.add(Config.get_sensitive_words_nickname())  # 添加敏感词
        return dfa.valid(nickname)  # 校验敏感词

    class Meta:
        db_table = "member"
        verbose_name = "会员"


class MemberNameLog(models.Model):
    member = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='成员', on_delete=models.PROTECT)
    old_name = models.CharField(verbose_name='昵称', max_length=100, null=True, blank=True)
    new_name = models.CharField(verbose_name='昵称', max_length=100, null=True, blank=True)
    create_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'member_name_log'
        verbose_name = '昵称修改日志'
        index_together = ('create_time',)
        ordering = ('-id',)


class MemberRecord(models.Model):
    DEFAULT = 0
    INSERT = 1
    DELETE = 2
    COMMENT = 3
    LIKE = 4
    COLLECT = 5
    LOGIN = 6
    BROWSE = 7

    OPERATE_CHOICE = (
        (INSERT, '添加'),
        (DELETE, '删除'),
        (COMMENT, '评论'),
        (LIKE, '点赞'),
        (COLLECT, '收藏'),
        (LOGIN, '登录'),
        (BROWSE, '浏览'),
    )
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey(
        ct_field="content_type",
        fk_field="object_id"
    )
    member = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='会员', on_delete=models.PROTECT)
    operate = models.PositiveIntegerField(verbose_name='用户操作', choices=OPERATE_CHOICE, default=DEFAULT)
    describe = models.CharField(verbose_name='记录描述', max_length=200, null=True)
    extra = models.CharField(verbose_name='数据', max_length=500, null=True)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True, editable=False)

    class Meta:
        db_table = 'member_record'
        verbose_name = '操作纪录表'


